package org.example.springbootproject.config;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

@Component
public class JwtUtil {

    // 和你的 ExamServiceImpl 中一致
    public static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    public static final long EXPIRATION = 60 * 60 * 1000;
    // 设置刷新缓冲时间为 5 分钟：即在 token 剩余时间小于 10 分钟时才刷新
    private static final long REFRESH_LEEWAY = 10 * 60 * 1000; // 10 minutes

    // 生成 Token
    public String generateToken(String username, String role) {
        return Jwts.builder()
                .setSubject(username)
                .claim("role", role)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SECRET_KEY)
                .compact();
    }


    // 刷新 token：仅当 token 即将过期时才刷新
    public String refreshToken(String oldToken) {
        Jws<Claims> claimsJws = Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(oldToken);

        Claims claims = claimsJws.getBody();
        Date expiration = claims.getExpiration();
        long currentTimeMillis = System.currentTimeMillis();

        // 如果 token 还未进入缓冲期，则不刷新
        if (expiration.getTime() - currentTimeMillis > REFRESH_LEEWAY) {
            return null; // 表示无需刷新
        }

        // 否则刷新 token
        String username = claims.getSubject();
        String role = claims.get("role", String.class);

        return Jwts.builder()
                .setSubject(username)
                .claim("role", role)
                .setExpiration(new Date(currentTimeMillis + EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }


    // 解析 Token
    public String extractUsername(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    // 验证 Token 是否有效
    public boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    // 获取 Token 中的角色
    public String extractRole(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .get("role", String.class);
    }
}
